package com.lifeverse.service;

import com.lifeverse.entity.Decision;
import com.lifeverse.service.RuleEngine.RuleActionResult;
import com.lifeverse.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 规则动作执行器
 * 负责执行规则定义的动作
 */
@Slf4j
@Service
public class RuleActionExecutor {
    
    /**
     * 执行规则动作
     */
    public RuleActionResult execute(String actions, Decision decision, Map<String, Object> context) {
        log.debug("执行规则动作 - 决策ID: {}", decision.getId());
        
        try {
            // 解析动作（简化实现）
            Map<String, Object> actionMap = JsonUtils.fromJson(actions, Map.class);
            if (actionMap == null) {
                // 如果不是JSON格式，尝试简单字符串动作
                return executeSimpleAction(actions, decision, context);
            }
            
            return executeComplexAction(actionMap, decision, context);
            
        } catch (Exception e) {
            log.error("规则动作执行失败: {}", actions, e);
            return createFailedResult("动作执行异常: " + e.getMessage());
        }
    }
    
    /**
     * 执行简单动作
     */
    private RuleActionResult executeSimpleAction(String actions, Decision decision, Map<String, Object> context) {
        Map<String, Object> results = new HashMap<>();
        
        if (actions.contains("increaseEnergy")) {
            return executeIncreaseEnergyAction(actions, decision, results);
        }
        
        if (actions.contains("increaseHealth")) {
            return executeIncreaseHealthAction(actions, decision, results);
        }
        
        if (actions.contains("increaseWisdom")) {
            return executeIncreaseWisdomAction(actions, decision, results);
        }
        
        if (actions.contains("increaseCreativity")) {
            return executeIncreaseCreativityAction(actions, decision, results);
        }
        
        if (actions.contains("increaseCollaboration")) {
            return executeIncreaseCollaborationAction(actions, decision, results);
        }
        
        if (actions.contains("setRecommendation")) {
            return executeSetRecommendationAction(actions, decision, results);
        }
        
        if (actions.contains("logEvent")) {
            return executeLogEventAction(actions, decision, results);
        }
        
        // 默认动作
        results.put("action", "default");
        results.put("message", "执行默认动作");
        return createSuccessResult(results);
    }
    
    /**
     * 执行复杂动作
     */
    private RuleActionResult executeComplexAction(Map<String, Object> actionMap, Decision decision, 
                                                Map<String, Object> context) {
        Map<String, Object> results = new HashMap<>();
        boolean allSuccess = true;
        
        for (Map.Entry<String, Object> entry : actionMap.entrySet()) {
            String actionType = entry.getKey();
            Object actionValue = entry.getValue();
            
            RuleActionResult actionResult = executeSingleAction(actionType, actionValue, decision, context);
            
            if (actionResult.isSuccess()) {
                results.putAll(actionResult.getResults());
            } else {
                allSuccess = false;
                results.put(actionType + "_error", actionResult.getErrorMessage());
            }
        }
        
        if (allSuccess) {
            return createSuccessResult(results);
        } else {
            return createPartialSuccessResult(results);
        }
    }
    
    /**
     * 执行单个动作
     */
    private RuleActionResult executeSingleAction(String actionType, Object actionValue, Decision decision, 
                                               Map<String, Object> context) {
        Map<String, Object> results = new HashMap<>();
        
        switch (actionType) {
            case "modifyAttribute":
                return executeModifyAttributeAction(actionValue, decision, results);
            case "setRecommendation":
                return executeSetRecommendationAction(actionValue, decision, results);
            case "createEvent":
                return executeCreateEventAction(actionValue, decision, results);
            case "updateContext":
                return executeUpdateContextAction(actionValue, decision, context, results);
            case "calculateScore":
                return executeCalculateScoreAction(actionValue, decision, results);
            case "triggerNotification":
                return executeTriggerNotificationAction(actionValue, decision, results);
            case "scheduleTask":
                return executeScheduleTaskAction(actionValue, decision, results);
            default:
                results.put("unknownAction", actionType);
                return createSuccessResult(results);
        }
    }
    
    /**
     * 执行增加能量动作
     */
    private RuleActionResult executeIncreaseEnergyAction(String actions, Decision decision, Map<String, Object> results) {
        try {
            // 解析增加值
            String[] parts = actions.split("increaseEnergy");
            BigDecimal increaseValue = BigDecimal.valueOf(10); // 默认值
            
            if (parts.length > 1) {
                String valueStr = parts[1].trim().replaceAll("[^0-9.]", "");
                if (!valueStr.isEmpty()) {
                    increaseValue = new BigDecimal(valueStr);
                }
            }
            
            BigDecimal currentEnergy = decision.getLifeEntity().getEnergyLevel();
            BigDecimal newEnergy = currentEnergy.add(increaseValue).min(BigDecimal.valueOf(100));
            decision.getLifeEntity().setEnergyLevel(newEnergy);
            
            results.put("action", "increaseEnergy");
            results.put("increaseValue", increaseValue);
            results.put("newEnergyLevel", newEnergy);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("增加能量失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行增加健康动作
     */
    private RuleActionResult executeIncreaseHealthAction(String actions, Decision decision, Map<String, Object> results) {
        try {
            BigDecimal increaseValue = BigDecimal.valueOf(5);
            BigDecimal currentHealth = decision.getLifeEntity().getHealthScore();
            BigDecimal newHealth = currentHealth.add(increaseValue).min(BigDecimal.valueOf(100));
            decision.getLifeEntity().setHealthScore(newHealth);
            
            results.put("action", "increaseHealth");
            results.put("increaseValue", increaseValue);
            results.put("newHealthScore", newHealth);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("增加健康失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行增加智慧动作
     */
    private RuleActionResult executeIncreaseWisdomAction(String actions, Decision decision, Map<String, Object> results) {
        try {
            BigDecimal increaseValue = BigDecimal.valueOf(8);
            BigDecimal currentWisdom = decision.getLifeEntity().getWisdomScore();
            BigDecimal newWisdom = currentWisdom.add(increaseValue);
            decision.getLifeEntity().setWisdomScore(newWisdom);
            
            results.put("action", "increaseWisdom");
            results.put("increaseValue", increaseValue);
            results.put("newWisdomScore", newWisdom);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("增加智慧失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行增加创造力动作
     */
    private RuleActionResult executeIncreaseCreativityAction(String actions, Decision decision, Map<String, Object> results) {
        try {
            BigDecimal increaseValue = BigDecimal.valueOf(6);
            BigDecimal currentCreativity = decision.getLifeEntity().getCreativityScore();
            BigDecimal newCreativity = currentCreativity.add(increaseValue);
            decision.getLifeEntity().setCreativityScore(newCreativity);
            
            results.put("action", "increaseCreativity");
            results.put("increaseValue", increaseValue);
            results.put("newCreativityScore", newCreativity);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("增加创造力失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行增加协作能力动作
     */
    private RuleActionResult executeIncreaseCollaborationAction(String actions, Decision decision, Map<String, Object> results) {
        try {
            BigDecimal increaseValue = BigDecimal.valueOf(4);
            BigDecimal currentCollaboration = decision.getLifeEntity().getCollaborationScore();
            BigDecimal newCollaboration = currentCollaboration.add(increaseValue).min(BigDecimal.valueOf(100));
            decision.getLifeEntity().setCollaborationScore(newCollaboration);
            
            results.put("action", "increaseCollaboration");
            results.put("increaseValue", increaseValue);
            results.put("newCollaborationScore", newCollaboration);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("增加协作能力失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行设置推荐动作
     */
    private RuleActionResult executeSetRecommendationAction(Object actionValue, Decision decision, Map<String, Object> results) {
        try {
            String recommendation;
            if (actionValue instanceof String) {
                recommendation = (String) actionValue;
            } else if (actionValue instanceof Map) {
                Map<String, Object> recMap = (Map<String, Object>) actionValue;
                recommendation = recMap.getOrDefault("message", "系统推荐").toString();
            } else {
                recommendation = "基于规则的推荐";
            }
            
            results.put("action", "setRecommendation");
            results.put("recommendation", recommendation);
            results.put("timestamp", System.currentTimeMillis());
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("设置推荐失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行修改属性动作
     */
    private RuleActionResult executeModifyAttributeAction(Object actionValue, Decision decision, Map<String, Object> results) {
        try {
            if (actionValue instanceof Map) {
                Map<String, Object> modifyMap = (Map<String, Object>) actionValue;
                
                for (Map.Entry<String, Object> entry : modifyMap.entrySet()) {
                    String attribute = entry.getKey();
                    Object value = entry.getValue();
                    
                    modifyLifeEntityAttribute(decision, attribute, value, results);
                }
            }
            
            results.put("action", "modifyAttribute");
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("修改属性失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行创建事件动作
     */
    private RuleActionResult executeCreateEventAction(Object actionValue, Decision decision, Map<String, Object> results) {
        try {
            String eventType = "RULE_TRIGGERED";
            String eventMessage = "规则触发事件";
            
            if (actionValue instanceof Map) {
                Map<String, Object> eventMap = (Map<String, Object>) actionValue;
                eventType = eventMap.getOrDefault("type", eventType).toString();
                eventMessage = eventMap.getOrDefault("message", eventMessage).toString();
            } else if (actionValue instanceof String) {
                eventMessage = (String) actionValue;
            }
            
            results.put("action", "createEvent");
            results.put("eventType", eventType);
            results.put("eventMessage", eventMessage);
            results.put("timestamp", System.currentTimeMillis());
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("创建事件失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行更新上下文动作
     */
    private RuleActionResult executeUpdateContextAction(Object actionValue, Decision decision, 
                                                      Map<String, Object> context, Map<String, Object> results) {
        try {
            if (actionValue instanceof Map) {
                Map<String, Object> updateMap = (Map<String, Object>) actionValue;
                context.putAll(updateMap);
            }
            
            results.put("action", "updateContext");
            results.put("updatedKeys", actionValue instanceof Map ? ((Map<?, ?>) actionValue).keySet() : "unknown");
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("更新上下文失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行计算分数动作
     */
    private RuleActionResult executeCalculateScoreAction(Object actionValue, Decision decision, Map<String, Object> results) {
        try {
            BigDecimal score = BigDecimal.ZERO;
            
            if (actionValue instanceof Map) {
                Map<String, Object> scoreMap = (Map<String, Object>) actionValue;
                String formula = scoreMap.getOrDefault("formula", "default").toString();
                score = calculateScoreByFormula(formula, decision);
            } else {
                // 默认计算综合分数
                score = decision.getLifeEntity().getWisdomScore()
                        .add(decision.getLifeEntity().getCreativityScore())
                        .add(decision.getLifeEntity().getCollaborationScore())
                        .divide(BigDecimal.valueOf(3), 2, java.math.RoundingMode.HALF_UP);
            }
            
            results.put("action", "calculateScore");
            results.put("calculatedScore", score);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("计算分数失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行触发通知动作
     */
    private RuleActionResult executeTriggerNotificationAction(Object actionValue, Decision decision, Map<String, Object> results) {
        try {
            String notificationType = "INFO";
            String message = "规则触发通知";
            
            if (actionValue instanceof Map) {
                Map<String, Object> notifyMap = (Map<String, Object>) actionValue;
                notificationType = notifyMap.getOrDefault("type", notificationType).toString();
                message = notifyMap.getOrDefault("message", message).toString();
            } else if (actionValue instanceof String) {
                message = (String) actionValue;
            }
            
            results.put("action", "triggerNotification");
            results.put("notificationType", notificationType);
            results.put("notificationMessage", message);
            results.put("recipient", "LifeEntity_" + decision.getLifeEntity().getId());
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("触发通知失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行调度任务动作
     */
    private RuleActionResult executeScheduleTaskAction(Object actionValue, Decision decision, Map<String, Object> results) {
        try {
            String taskType = "FOLLOW_UP";
            long delayMinutes = 60; // 默认1小时后
            
            if (actionValue instanceof Map) {
                Map<String, Object> taskMap = (Map<String, Object>) actionValue;
                taskType = taskMap.getOrDefault("type", taskType).toString();
                delayMinutes = Long.parseLong(taskMap.getOrDefault("delayMinutes", delayMinutes).toString());
            }
            
            results.put("action", "scheduleTask");
            results.put("taskType", taskType);
            results.put("delayMinutes", delayMinutes);
            results.put("scheduledTime", System.currentTimeMillis() + delayMinutes * 60 * 1000);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("调度任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行记录事件动作
     */
    private RuleActionResult executeLogEventAction(String actions, Decision decision, Map<String, Object> results) {
        try {
            String logMessage = "规则执行日志";
            
            if (actions.contains("logEvent")) {
                String[] parts = actions.split("logEvent");
                if (parts.length > 1) {
                    logMessage = parts[1].trim().replace("\"", "");
                }
            }
            
            results.put("action", "logEvent");
            results.put("logMessage", logMessage);
            results.put("timestamp", System.currentTimeMillis());
            
            log.info("规则日志 - 决策ID: {}, 消息: {}", decision.getId(), logMessage);
            
            return createSuccessResult(results);
            
        } catch (Exception e) {
            return createFailedResult("记录事件失败: " + e.getMessage());
        }
    }
    
    /**
     * 修改生命体属性
     */
    private void modifyLifeEntityAttribute(Decision decision, String attribute, Object value, Map<String, Object> results) {
        BigDecimal numericValue = new BigDecimal(value.toString());
        
        switch (attribute) {
            case "energyLevel":
                BigDecimal newEnergy = decision.getLifeEntity().getEnergyLevel().add(numericValue).min(BigDecimal.valueOf(100));
                decision.getLifeEntity().setEnergyLevel(newEnergy);
                results.put("modified_energyLevel", newEnergy);
                break;
            case "healthScore":
                BigDecimal newHealth = decision.getLifeEntity().getHealthScore().add(numericValue).min(BigDecimal.valueOf(100));
                decision.getLifeEntity().setHealthScore(newHealth);
                results.put("modified_healthScore", newHealth);
                break;
            case "wisdomScore":
                BigDecimal newWisdom = decision.getLifeEntity().getWisdomScore().add(numericValue);
                decision.getLifeEntity().setWisdomScore(newWisdom);
                results.put("modified_wisdomScore", newWisdom);
                break;
            case "creativityScore":
                BigDecimal newCreativity = decision.getLifeEntity().getCreativityScore().add(numericValue);
                decision.getLifeEntity().setCreativityScore(newCreativity);
                results.put("modified_creativityScore", newCreativity);
                break;
            case "collaborationScore":
                BigDecimal newCollaboration = decision.getLifeEntity().getCollaborationScore().add(numericValue).min(BigDecimal.valueOf(100));
                decision.getLifeEntity().setCollaborationScore(newCollaboration);
                results.put("modified_collaborationScore", newCollaboration);
                break;
        }
    }
    
    /**
     * 根据公式计算分数
     */
    private BigDecimal calculateScoreByFormula(String formula, Decision decision) {
        switch (formula) {
            case "wisdom_creativity_avg":
                return decision.getLifeEntity().getWisdomScore()
                        .add(decision.getLifeEntity().getCreativityScore())
                        .divide(BigDecimal.valueOf(2), 2, java.math.RoundingMode.HALF_UP);
            case "all_attributes_avg":
                return decision.getLifeEntity().getWisdomScore()
                        .add(decision.getLifeEntity().getCreativityScore())
                        .add(decision.getLifeEntity().getCollaborationScore())
                        .add(decision.getLifeEntity().getEnergyLevel())
                        .add(decision.getLifeEntity().getHealthScore())
                        .divide(BigDecimal.valueOf(5), 2, java.math.RoundingMode.HALF_UP);
            case "potential_score":
                return decision.getLifeEntity().getWisdomScore()
                        .multiply(BigDecimal.valueOf(0.4))
                        .add(decision.getLifeEntity().getCreativityScore().multiply(BigDecimal.valueOf(0.6)));
            default:
                return decision.getLifeEntity().getWisdomScore();
        }
    }
    
    /**
     * 创建成功结果
     */
    private RuleActionResult createSuccessResult(Map<String, Object> results) {
        RuleActionResult result = new RuleActionResult();
        result.setSuccess(true);
        result.setResults(results);
        return result;
    }
    
    /**
     * 创建部分成功结果
     */
    private RuleActionResult createPartialSuccessResult(Map<String, Object> results) {
        RuleActionResult result = new RuleActionResult();
        result.setSuccess(true); // 部分成功也算成功
        result.setResults(results);
        return result;
    }
    
    /**
     * 创建失败结果
     */
    private RuleActionResult createFailedResult(String errorMessage) {
        RuleActionResult result = new RuleActionResult();
        result.setSuccess(false);
        result.setErrorMessage(errorMessage);
        result.setResults(new HashMap<>());
        return result;
    }
}